package com.wcs.exam.common.swagger;

import com.wcs.exam.common.base.BaseEnum;
import com.wcs.exam.common.base.annotation.SchemaEnum;
import io.swagger.v3.core.converter.AnnotatedType;
import io.swagger.v3.oas.models.media.Schema;
import org.springdoc.core.customizers.PropertyCustomizer;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.annotation.Annotation;

@Component
public class EnumPropertyCustomizer implements PropertyCustomizer {

    @Override
    public Schema<?> customize(Schema schema, AnnotatedType type) {
        if (type.getCtxAnnotations() == null) {
            return schema;
        }

        StringBuilder description = new StringBuilder();

        for (Annotation ctxAnnotation : type.getCtxAnnotations()) {
            if (ctxAnnotation.annotationType().equals(SchemaEnum.class)) {
                String desc = ((SchemaEnum) ctxAnnotation).description();
                if (StringUtils.hasText(desc)) {
                    description.append(desc).append("(");
                }
                Class<? extends BaseEnum> clazz = ((SchemaEnum) ctxAnnotation).value();
                description.append(BaseEnum.getInfo(clazz));
                if (StringUtils.hasText(desc)) {
                    description.append(")");
                }
            }
        }
        if (!description.isEmpty()) {
            schema.setDescription(description.toString());
        }
        return schema;
    }
}